#include "add_sub1.h"
#include "ui_add_sub1.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmessagebox.h"
#include "stdlib.h"
#include "QTime"
#include"qrandom.h"
add_sub::add_sub(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::add_sub)
{
    QRandomGenerator(QTime(0,0,0).secsTo(QTime::currentTime()));
    ui->setupUi(this);
    ui->lineEdit_2->setFocus();

    a = (rand() % 20);
    b = (rand() % 20);
    sum = a + b;
    QString a_str = QString::number(a);
    QString b_str = QString::number(b);
    QString line = a_str + "+" + b_str + "=";
    ui->lineEdit->setText(line);
    flag = 1;
}

add_sub::~add_sub()
{
    delete ui;
}

void add_sub::on_pushButton_clicked()
{
    check_sum();
    QString a_str;
    QString b_str;
    QString line;

    switch(flag)
    {
        case 0 :
        a = (rand() % 20);
        b = (rand() % 20);
        sum = a + b;
        a_str = QString::number(a);
        b_str = QString::number(b);
        line = a_str + "+" + b_str + "=";
        ui->lineEdit->setText(line);
        flag = 1;
        break;

        case 1:
        a = (rand() % 20);
        b = (rand() % 20);
        if(a<b)
        {
            int temp=0;
            temp=a;
            a=b;
            b=temp;
        }
        sum = a - b;
        a_str = QString::number(a);
        b_str = QString::number(b);
        line = a_str + "-" + b_str + "=";
        ui->lineEdit->setText(line);
        flag = 0;
        break;

    default: printf("flag is error!\n"); break;
    }
    ui->lineEdit_2->setFocus();

}

void add_sub::on_pushButton_2_clicked()
{
    check_sum();
    ui->lineEdit_2->setFocus();

    QString total_number = "total number:";
    QString total_str = QString::number(total);
    total_number = total_number + total_str;

    QString right_number = ", right number:";
    QString right_str = QString::number(right);
    right_number = right_number + right_str;

    QString wrong_number = ", wrong number:";
    QString wrong_str = QString::number(wrong);
    wrong_number = wrong_number + wrong_str;

    QString message_output = total_number + right_number + wrong_number;

    QMessageBox::information(NULL, "your answer", message_output, QMessageBox::Yes);

    total = 0;
    right = 0;
    wrong = 0;
}

void add_sub::on_pushButton_3_clicked()
{
    emit sendsignal();
    add_sub::close();
}

void add_sub::check_sum()
{
    QString my_sum_str = ui->lineEdit_2->text();
    int my_sum = my_sum_str.toInt();

    total++;
    if(my_sum == sum){
        right++;

    }else{
        wrong++;
        QString sum_str = QString::number(sum);
        QString warn_str="the right answer is:"+sum_str;
        QMessageBox::information(NULL, "wrong!",warn_str , QMessageBox::Yes);

    }
    ui->lineEdit_2->clear();
}
